<template>
  <div class="controls">
    <input
      autocomplete="off"
      :value="currentValue"
      class="itxt"
      @blur="handleBlur"
      @keyup.enter="handleKeyUp"
    />
    <button
      class="plus"
      @click="changeValue(1)"
      :disabled="currentValue === max"
    >
      <i class="iconfont icon-iconxiangshangjiantou01"></i>
    </button>
    <button
      class="mins"
      @click="changeValue(-1)"
      :disabled="currentValue === min"
    >
      <i class="iconfont icon-iconxiangxiajiantou01"></i>
    </button>
  </div>
</template>

<script>
export default {
  name: "NumInput",
  props: {
    // input 框的value值
    value: {
      type: Number,
      require: true,
    },
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 50,
    },
  },
  components: {},
  data() {
    return {
      currentValue: this.value,
    };
  },
  methods: {
    changeValue(val) {
      this.currentValue += val;
    },
    handleBlur(e) {
      this.currentValue = +e.target.value;
    },
    handleKeyUp(e) {
      this.currentValue = +e.target.value;
    },
  },
  watch: {
    currentValue(newVal, oldVal) {
      let newValue = Math.ceil(+newVal); // 输入小数，向上取整
      if (newValue > this.max) {
        newValue = this.max;
      } else if (newValue < this.min) {
        newValue = this.min;
      }
      if (Number.isNaN(newValue)) {
        // 输入非数字，等于上一次的值
        newValue = oldVal;
      }

      this.currentValue = newValue;
      /* 把数值传给父组件  */
      this.$emit("input", this.currentValue);
    },
  },
};
</script>
<style lang='less' scoped>
.controls {
  width: 58px;
  position: relative;
  float: left;
  margin-right: 15px;
  .itxt {
    width: 42px;
    height: 36px;
    border: 1px solid #ddd;
    color: #555;
    float: left;
    border-right: 0;
    text-align: center;
  }
  .plus,
  .mins {
    width: 20px;
    text-align: center;
    height: 20px;
    line-height: 17px;
    background: #f1f1f1;
    color: #666;
    position: absolute;
    right: -8px;
    border: 1px solid #ccc;
    display: flex;
    justify-content: center;
    i {
      font-size: 12px;
    }
    &:disabled {
      color: #ccc;
      cursor: not-allowed;
    }
  }
  .mins {
    right: -8px;
    top: 20px;
    border-top: 0;
  }
  .plus {
    right: -8px;
  }
}
</style>